import React, { Component } from 'react';
import matchPath from '../utils/matchPath';
import RouterContext from '../RouterContext';

export default class Route extends Component {
  render() {
    return (
      <RouterContext.Consumer>
        {(context) => {
          const { path, children, component, render } = this.props;
          const { location } = context;

          /* const match = location.pathname === path; */
          const match = path ? matchPath(location.pathname, this.props) : context.match;
          const cProps = { ...context, match, location };
          /* 渲染优先级：children > component > render */

          /* 更新 RouterContext */
          return (
            <RouterContext.Provider value={cProps}>
              {match
                ? children
                  ? typeof children === 'function'
                    ? children(cProps)
                    : children
                  : component
                  ? React.createElement(component, cProps)
                  : render
                  ? render(cProps)
                  : null
                : typeof children === 'function'
                ? children(cProps)
                : null}
            </RouterContext.Provider>
          );
        }}
      </RouterContext.Consumer>
    );
  }
}
